package com.danger.Service;

import android.content.Context;
import android.content.Intent;
import android.os.Message;

import com.danger.Activity.MainActivity;
import com.danger.Db.ThreadDao;
import com.danger.Db.ThreadDaoImpl;
import com.danger.Model.FileInfo;
import com.danger.Model.ThreadInfo;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 下载任务类
 * Created by 俊 on 2016/6/8.
 */
public class DownloadTask {

    private FileInfo fileInfo;
    private ThreadDao threadDao;
    private int finished = 0;
    public boolean isPause = false;

    public DownloadTask(Context context, FileInfo fileInfo) {
        this.fileInfo = fileInfo;
        threadDao = new ThreadDaoImpl(context);
    }

    public void downLoad() {
        //读取数据库中的线程信息
        List<ThreadInfo> threadInfos = threadDao.getThreads(fileInfo.getUrl());
        ThreadInfo threadInfo = null;
        if (threadInfos.size() == 0) {
            //初始化线程信息参数
            threadInfo = new ThreadInfo(0, fileInfo.getUrl(), 0, fileInfo.getLength(), 0);
        } else {
            threadInfo = threadInfos.get(0);
        }
        //创建子线程进行下载
        new DownloadThread(threadInfo).start();

    }

    /**
     * 下载线程
     */
    class DownloadThread extends Thread {

        private ThreadInfo threadInfo;

        public DownloadThread(ThreadInfo threadInfo) {
            this.threadInfo = threadInfo;
        }

        @Override
        public void run() {
            super.run();
            //向数据库中插入一条信息
            if (!threadDao.isExists(threadInfo.getUrl(), threadInfo.getId())) {
                threadDao.insertThread(threadInfo);
            }
            HttpURLConnection conn = null;
            RandomAccessFile raf = null;
            InputStream inputStream = null;
            try {
                URL url = new URL(threadInfo.getUrl());
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3000);
                conn.setRequestMethod("GET");
                //设置下载位置
                int start = threadInfo.getStart() + threadInfo.getFinished();
                conn.setRequestProperty("Range", "bytes=" + start + "-" + threadInfo.getEnd());
                //设置文件写入位置
                File file = new File(DownloadService.DOWNLOAD_PATH, fileInfo.getFileName());
                raf = new RandomAccessFile(file, "rwd");
                raf.seek(start);

                Intent intent = new Intent(DownloadService.ACTION_UPDATE);

                //开始下载
                finished = threadInfo.getFinished() + finished;
                if (conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL) {
                    //读取数据
                    inputStream = conn.getInputStream();
                    byte[] buffer = new byte[1024 * 4];
                    int len = -1;
//                    long time = System.currentTimeMillis();
                    while ((len = inputStream.read(buffer)) != -1) {
                        //写入文件
                        raf.write(buffer, 0, len);
                        finished = finished + len;
//                        if (System.currentTimeMillis() - time > 500) {
//                            time = System.currentTimeMillis();
                        intent.putExtra("finished", finished * 100 / fileInfo.getLength());
                        //下载进度发送广播给Activity
//                            context.sendBroadcast(intent);
                        //下载暂停时保存下载进度
                        if (isPause) {
                            threadDao.updateThread(threadInfo.getUrl(), threadInfo.getId(), finished);
                            return;
                        }
                        Message message = Message.obtain();
                        message.obj = finished * 100 / fileInfo.getLength();
                        message.what = 1;
                        MainActivity.handler.sendMessage(message);
                    }
                    //删除线程信息
                    threadDao.deleteThread(threadInfo.getUrl(), threadInfo.getId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    conn.disconnect();
                    inputStream.close();
                    raf.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}